<template>
  <el-card>
    <div slot="header">
      <div class="flex justify-between items-center">
        <span>菜品管理</span>
        <el-button type="primary" @click="dialogVisible = true">新增菜品</el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-input v-model="searchName" placeholder="输入菜品名称搜索"></el-input>
      </el-col>
      <el-col :span="6">
        <el-select v-model="searchType" placeholder="选择菜品类型">
          <el-option label="全部" value=""></el-option>
          <el-option label="驴肉火烧" value="火烧"></el-option>
          <el-option label="小吃" value="小吃"></el-option>
          <el-option label="饮品" value="饮品"></el-option>
        </el-select>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="getFoodList">查询</el-button>
      </el-col>
    </el-row>

    <!-- 菜品列表 -->
    <el-table :data="foodList" border>
      <el-table-column prop="foodId" label="ID" width="80"></el-table-column>
      <el-table-column prop="foodName" label="菜品名称"></el-table-column>
      <el-table-column prop="foodType" label="类型"></el-table-column>
      <el-table-column prop="foodPrice" label="价格" :formatter="formatPrice"></el-table-column>
      <el-table-column prop="foodStock" label="库存"></el-table-column>
      <el-table-column prop="foodStatus" label="状态">
        <template #default="scope">
          <el-switch 
            v-model="scope.row.foodStatus" 
            active-value="在售" 
            inactive-value="下架"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" danger @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right;"
    ></el-pagination>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="foodForm" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="菜品名称" prop="foodName">
          <el-input v-model="formData.foodName"></el-input>
        </el-form-item>
        <el-form-item label="菜品类型" prop="foodType">
          <el-select v-model="formData.foodType">
            <el-option label="驴肉火烧" value="火烧"></el-option>
            <el-option label="小吃" value="小吃"></el-option>
            <el-option label="饮品" value="饮品"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="foodPrice">
          <el-input v-model="formData.foodPrice" type="number"></el-input>
        </el-form-item>
        <el-form-item label="库存" prop="foodStock">
          <el-input v-model="formData.foodStock" type="number"></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            action="/api/upload"
            list-type="picture"
            :on-success="handleUploadSuccess"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from '../utils/axios';

// 状态管理
const foodList = ref([]);
const searchName = ref('');
const searchType = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogVisible = ref(false);
const dialogTitle = ref('新增菜品');
const foodForm = ref(null); // 表单引用
const formData = ref({
  foodId: '',
  foodName: '',
  foodType: '',
  foodPrice: '',
  foodStock: '',
  foodImage: ''
});

// 表单验证规则
const rules = ref({
  foodName: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' }
  ],
  foodType: [
    { required: true, message: '请选择菜品类型', trigger: 'change' }
  ],
  foodPrice: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  foodStock: [
    { required: true, message: '请输入库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' }
  ]
});

// 格式化价格
const formatPrice = (row) => {
  return `¥${row.foodPrice}`;
};

// 获取菜品列表
const getFoodList = async () => {
  try {
    const res = await axios.get('/food/list', {
      params: {
        name: searchName.value,
        type: searchType.value,
        page: currentPage.value,
        size: pageSize.value
      }
    });
    foodList.value = res.data;
    total.value = res.total;
  } catch (error) {
    console.error('获取菜品列表失败:', error);
    ElMessage.error('获取菜品列表失败');
  }
};

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val;
  getFoodList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getFoodList();
};

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await axios.post('/food/updateStatus', {
      foodId: row.foodId,
      foodStatus: row.foodStatus
    });
    ElMessage.success('状态更新成功');
  } catch (error) {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
    // 失败时回滚状态
    row.foodStatus = row.foodStatus === '在售' ? '下架' : '在售';
  }
};

// 编辑菜品
const handleEdit = (row) => {
  dialogTitle.value = '编辑菜品';
  formData.value = { ...row };
  dialogVisible.value = true;
};

// 删除菜品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该菜品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await axios.post('/food/delete', {
      foodId: row.foodId
    });
    
    ElMessage.success('删除成功');
    getFoodList();
  } catch (error) {
    // 如果用户取消则不提示错误
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 上传图片成功回调
const handleUploadSuccess = (response) => {
  if (response.state === 'success') {
    formData.value.foodImage = response.url;
    ElMessage.success('上传成功');
  }
};

// 保存菜品
const handleSave = async () => {
  try {
    // 先验证表单
    if (foodForm.value) {
      await foodForm.value.validate();
    }
    
    if (formData.value.foodId) {
      // 编辑操作
      await axios.post('/food/update', formData.value);
      ElMessage.success('更新成功');
    } else {
      // 新增操作
      await axios.post('/food/add', formData.value);
      ElMessage.success('新增成功');
    }
    dialogVisible.value = false;
    getFoodList();
  } catch (error) {
    console.error('操作失败:', error);
    // 如果是表单验证失败则不显示错误消息
    if (!error || error.name !== 'ValidationError') {
      ElMessage.error('操作失败');
    }
  }
};

// 初始化
onMounted(() => {
  getFoodList();
});
</script>

<style scoped>
.flex {
  display: flex;
}
.justify-between {
  justify-content: space-between;
}
.items-center {
  align-items: center;
}
</style>
